//引入express模块
const {
    response,
    query
} = require("express")
const express = require("express")
const {
    request
} = require("http")
//引入path模块
const path = require("path")
//创建应用对象
const app = express()

app.use(express.urlencoded())
app.use(express.json())


/* // 手写一个类似与body的form表单类型文件处理的 中间件
app.use("/user-post", (request, response, next) => {
    let dataStr = ""
    //绑定data事件，读取响应体的内容
    request.on("data", chunk => {
        // console.log(chunk.toString());

        // 将空字符串与每次读取的响应体内容做累加
        dataStr += chunk.toString()
    })

    // 绑定end事件，读取完后打印响应体的内容，此时内容的格式为form表单（name=123&age=31&gender=m），需要转化为对象
    request.on("end", chunk => {
        // console.log("okkk", dataStr.split("&")); //name=123&age=31&gender=m


        // 写法一：
        // const obj = {}
        // dataStr.split("&").forEach((item) => {
        //     // console.log(item); //name=123  age=31  gender=m
        //     // console.log(item.split("="));
        //     const [key, value] = item.split("=")
        //     obj[key] = value //{ name: '123', age: '31', gender: 'm' }
        // })

        // 写法二：
        const obj = dataStr.split("&").reduce((prev, current) => {
            const [key, value] = current.split("=")
            prev[key] = value
            return prev
        }, {})
        request.body = obj
        next()
    })
}) */

// 搭建学生信息接口（get请求）
app.get("/user", (request, response) => {
    const {
        userId
    } = request.query

    if (userId !== "001") {
        return response.send({
            code: 10001,
            msg: "查询失败",
            data: null
        })
    }
    response.send({
        code: 10000,
        msg: "查询成功",
        data: {
            name: "liuMin",
            age: 31,
            gender: "男"
        }
    })

})
//添加个人信息
app.post("/post", (request, response) => {
    const {
        name,
        age,
        gender
    } = request.body


    if (!name || !age || !gender) {
        return response.send({
            code: 10001,
            msg: "添加失败",
            data: null
        })
    }

    response.send({
        code: 10000,
        msg: "添加成功",
        data: {
            name: "liuMin",
            age: 31,
            gender: "m"
        }
    })
})

app.put("/put", (request, response) => {
    const {
        name,
        age,
        gender
    } = request.body

    response.send({
        code: 10003,
        msg: "修改成功",
        data: {
            name: "xinXin",
            age: 28,
            gender: "f"
        }
    })
})
app.delete("/delete", (request, response) => {
    const {
        userId = 002
    } = request.query

    response.send({
        code: 10004,
        msg: "删除成功",
        data: {
            name: "xiaoMao",
            age: 23,
            gender: "f"
        }
    })
})


// 搭建接口（06.拦截练习）
app.get("/user-practice", (request, response) => {

    const token = request.headers.token
    console.log(token);

    if (!token) {
        return response.send({
            code: 10002,
            msg: "没有权限",
            data: null
        })
    }

    const {
        userId
    } = request.query

    if (userId !== "001") {
        return response.send({
            code: 10001,
            msg: "查询失败",
            data: null
        })
    }
    response.send({
        code: 10000,
        msg: "查询成功",
        data: {
            name: "liuMin",
            age: 31,
            gender: "男"
        }
    })

})

// 搭建接口（06.取消请求）
app.get("/user-delay", (request, response) => {

    setTimeout(() => {
        const token = request.headers.token
        if (!token) {
            return response.send({
                code: 10002,
                msg: "没有权限",
                data: null
            }) 
        }

        const {
            userId
        } = request.query

        if (userId !== "001") {
            return response.send({
                code: 10001,
                msg: "查询失败",
                data: null
            })
        }
        response.send({
            code: 10000,
            msg: "查询成功",
            data: {
                name: "liuMin",
                age: 31,
                gender: "男"
            }
        })
    }, 3000)

})

//搭建路由(01.axios简单使用)
app.get("/1", (request, response) => {
    const filePath = path.resolve(__dirname, "./01.axios简单使用.html")
    response.sendFile(filePath)
})
//搭建路由(01.axios简单使用2) 
app.get("/2", (request, response) => {
    const filePath = path.resolve(__dirname, "./01.axios简单使用2.html")
    response.sendFile(filePath)
})
//搭建路由(01.axios简单使用3)
app.get("/3", (request, response) => {
    const filePath = path.resolve(__dirname, "./01.axios简单使用3.html")
    response.sendFile(filePath)
})
//搭建路由(02.axios请求别名)
app.get("/4", (request, response) => {
    const filePath = path.resolve(__dirname, "./02.axios请求别名.html")
    response.sendFile(filePath)
})

//搭建路由(03.创建axios实例)
app.get("/5", (request, response) => {
    const filePath = path.resolve(__dirname, "./03.创建axios实例.html")
    response.sendFile(filePath)
})
//搭建路由(03.创建axios实例(1))
app.get("/6", (request, response) => {
    const filePath = path.resolve(__dirname, "./03.创建axios实例(2).html")
    response.sendFile(filePath)
})
//搭建路由(04.请求拦截)
app.get("/7", (request, response) => {
    const filePath = path.resolve(__dirname, "./04.请求拦截.html")
    response.sendFile(filePath)
})
//搭建路由(04.请求拦截(1))
app.get("/8", (request, response) => {
    const filePath = path.resolve(__dirname, "./04.请求拦截(1).html")
    response.sendFile(filePath)
})
//搭建路由(05.响应拦截)
app.get("/9", (request, response) => {
    const filePath = path.resolve(__dirname, "./05.响应拦截.html")
    response.sendFile(filePath)
})
//搭建路由(06.拦截练习)
app.get("/10", (request, response) => {
    const filePath = path.resolve(__dirname, "./06.拦截练习.html")
    response.sendFile(filePath)
})
//搭建路由(06.拦截练习(1))
app.get("/11", (request, response) => {
    const filePath = path.resolve(__dirname, "./06.拦截练习(1).html")
    response.sendFile(filePath)
})
//搭建路由(07.取消请求)
app.get("/12", (request, response) => {
    const filePath = path.resolve(__dirname, "./07.取消请求.html")
    response.sendFile(filePath)
})
//搭建路由(07.取消请求(1))
app.get("/13", (request, response) => {
    const filePath = path.resolve(__dirname, "./07.取消请求(1).html")
    response.sendFile(filePath)
})









//设置端口，开启路由
app.listen(8383, () => {
    console.log("服务器开启成功，请访问 http://127.0.0.1:8383");
})